package com.qdsgjsfk.vision.ui;

import android.text.Editable;
import android.text.TextWatcher;
import android.util.Log;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import com.jaeger.library.StatusBarUtil;
import com.qdsgjsfk.vision.R;
import com.qdsgjsfk.vision.base.BaseActivity;
import com.qdsgjsfk.vision.base.BaseApplication;
import com.qdsgjsfk.vision.model.DomainNameInfo;
import com.qdsgjsfk.vision.ui.widget.ClearEditText;
import com.qdsgjsfk.vision.util.NetUtil;
import com.qdsgjsfk.vision.util.UtilString;
import com.rest.business.RestProxy;
import com.rest.client.RestClient;
import com.rest.constant.Constant;
import com.rest.converter.ApiException;
import com.rest.response.IaBaseResponse;
import com.rest.response.LoginResponse;

import org.litepal.LitePal;

import java.util.List;

import butterknife.BindView;
import butterknife.OnClick;
import io.reactivex.Observer;
import io.reactivex.disposables.Disposable;
import util.PreferencesHelper;

/**
 * Created by HP on 2018/10/5.
 */

public class LoginActivity extends BaseActivity {

    @BindView(R.id.username)
    ClearEditText username;

    @BindView(R.id.password)
    ClearEditText password;

    @BindView(R.id.btn_login)
    TextView btn_login;

    @BindView(R.id.checkbox)
    ImageView checkbox;


    boolean isUsernameNull, isPasswordNull, isCheckBox;
    String domainName = "";

    @Override
    protected void initViews() {
        if (PreferencesHelper.getInstance().getBoolean( this, "isCheckBox" )) {
            checkbox.setImageResource( R.mipmap.check_focus );
            isCheckBox = true;
            username.setText( PreferencesHelper.getInstance().getString( this, "username" ) );
            password.setText( PreferencesHelper.getInstance().getString( this, "password" ) );
        } else {
            checkbox.setImageResource( R.mipmap.check );
            isCheckBox = false;
        }
//        PreferencesHelper.getInstance().set( this, "ipv4", "" );
        setLoginButtonState();
        StatusBarUtil.setTranslucentForImageView( this, 0, null );
    }

    @Override
    protected void initData() {
        //创建保存域名的数据库
        LitePal.getDatabase();
    }

    @OnClick(R.id.btn_login)
    void btn_login() {
        RestClient.getInstance().clearSession();
        String userName = this.username.getText().toString().trim();
        //查询缓存域名
        List<DomainNameInfo> queryList = LitePal.where( "account=?", userName ).find( DomainNameInfo.class );
        Log.e( "queryList----", queryList.size() + "" );
        if (queryList.size() > 0) {
            for (DomainNameInfo book : queryList) {
                Log.d( "queryList----", "book pages is " + book.getDomainName() );
                domainName = book.getDomainName();
                if (!UtilString.isEmpty( domainName )) {
                    //有缓存，直接调用登录接口
                    Constant.USER_HOST = book.getDomainName();
                    Constant.HOST = book.getDomainName();
                    PreferencesHelper.getInstance().set( LoginActivity.this, "domain", book.getDomainName() );
                    login();
                } else {
                    //无缓存，走原登录流程
                    domainName = "";
                    getDomain();
                }

            }
        } else {
            domainName = "";
            getDomain();
        }
    }

    @Override
    protected int getLayoutResource() {
        return R.layout.activity_login;
    }


    /**
     * 根据用户名获取域名
     *
     * @time 2020/6/4 8:56
     */
    private void getDomain() {
        showProgressDialog(LoginActivity.this);
        RestProxy.getInstance().getDomainName( username.getText().toString(), new Observer<IaBaseResponse>() {
            @Override
            public void onSubscribe(Disposable d) {
            }

            @Override
            public void onNext(IaBaseResponse iaBaseResponse) {
                dismissProgressDialog();
                Log.e( "域名====", iaBaseResponse.data );
                Constant.USER_HOST = iaBaseResponse.data;
                Constant.HOST = iaBaseResponse.data;
                domainName = iaBaseResponse.data;
                PreferencesHelper.getInstance().set( mContext, "domain", iaBaseResponse.data );
//                Constant.USER_HOST = "https://api-ext-bak.qdsgvision.com";
//                Constant.HOST = "https://api-ext-bak.qdsgvision.com";
//                domainName = "https://api-ext-bak.qdsgvision.com";
//                PreferencesHelper.getInstance().set( mContext, "domain", "https://api-ext-bak.qdsgvision.com" );
                login();
            }

            @Override
            public void onError(Throwable e) {
                dismissProgressDialog();
                NetUtil.onError( e, LoginActivity.this );
            }

            @Override
            public void onComplete() {

            }
        } );

    }


    private void login() {
        showProgressDialog( LoginActivity.this );
        RestProxy.getInstance().login( username.getText().toString(), password.getText().toString(), new Observer<LoginResponse>() {
            @Override
            public void onSubscribe(Disposable d) {
                BaseApplication.permission = false;
                BaseApplication.addUnChina = false;
                BaseApplication.addChinaNoId = false;
            }

            @Override
            public void onNext(LoginResponse loginResponse) {
                saveDomainName( username.getText().toString().trim(), true );
                PreferencesHelper.getInstance().set( LoginActivity.this, "username", username.getText().toString() );
                PreferencesHelper.getInstance().set( LoginActivity.this, "password", password.getText().toString() );
                PreferencesHelper.getInstance().set( LoginActivity.this, "token", loginResponse.data.token );
//                PreferencesHelper.getInstance().set(LoginActivity.this, "userId", loginResponse.data.userId);
//                PreferencesHelper.getInstance().set(LoginActivity.this, "perm", loginResponse.data.perm);
                PreferencesHelper.getInstance().set( LoginActivity.this, "isCheckBox", isCheckBox );
                //重新登录，设置为医师筛查模式
                PreferencesHelper.getInstance().set( LoginActivity.this, "model", 1 );//医生1
                RestClient.getInstance().token = loginResponse.data.token;
                startActivity( TypeActivity.class );
                for (String s : loginResponse.data.permission) {
                    if (s.equals( "1002" )) {
                        BaseApplication.permission = true;
                    }
                    if (s.equals( "1150" )) {
                        BaseApplication.addUnChina = true;
                    }
                    if (s.equals( "1149" )) {
                        BaseApplication.addChinaNoId = true;
                    }
                    if (s.equals( "1156" )) {
                        BaseApplication.faceAdd = true;
                    }
                    if (s.equals( "1157" )) {
                        BaseApplication.faceSearch = true;
                    }
                }
                finish();
            }

            @Override
            public void onError(Throwable e) {
                saveDomainName( username.getText().toString().trim(), false );
                try {
                    if (e instanceof ApiException) {
                        String errorMessage = ((ApiException) e).errorMessage;
                        Toast.makeText( LoginActivity.this, errorMessage, Toast.LENGTH_SHORT ).show();
                    } else {
                        Toast.makeText( LoginActivity.this, "网络不佳，请切换网络后重试", Toast.LENGTH_SHORT ).show();
                    }
                } catch (Exception exception) {
                    e.printStackTrace();
                }
            }

            @Override
            public void onComplete() {

            }
        } );
    }

    /**
     * 缓存域名到本地
     *
     * @time 2020/10/15 9:57
     */
    private void saveDomainName(String account, Boolean isLoginSuccess) {
        //查询本地域名
        dismissProgressDialog();
        List<DomainNameInfo> saveList = LitePal.where( "account=?", account ).find( DomainNameInfo.class );
        Log.e( "saveList----", saveList.size() + "" );
        if (saveList.size() == 0) {
            //第一次，保存域名
            if (isLoginSuccess) {
                DomainNameInfo domainNameInfo = new DomainNameInfo();
                domainNameInfo.setAccount( account );
                domainNameInfo.setDomainName( domainName );
                domainNameInfo.save();
            }

        } else {
            //更新域名
            if (isLoginSuccess) {
                DomainNameInfo domainNameInfo = new DomainNameInfo();
                domainNameInfo.setDomainName( domainName );
                domainNameInfo.updateAll( "account=?", account );
            } else {
                DomainNameInfo domainNameInfo = new DomainNameInfo();
                domainNameInfo.setDomainName( "" );
                domainNameInfo.updateAll( "account=?", account );
            }

        }
    }


    private void setLoginButtonState() {
        if (PreferencesHelper.getInstance().getString( this, "username" ).length() > 0) {
            isUsernameNull = true;
        }
        if (PreferencesHelper.getInstance().getString( this, "password" ).length() > 0) {
            isPasswordNull = true;
        }
        if (isUsernameNull && isPasswordNull) {
            btn_login.setBackgroundResource( R.drawable.item_bg_blue_button );
            btn_login.setEnabled( true );
        } else {
            btn_login.setEnabled( false );
        }
        username.addTextChangedListener( new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {

            }

            @Override
            public void afterTextChanged(Editable s) {
                if (s.toString().length() > 0) {
                    isUsernameNull = true;
                } else {
                    isUsernameNull = false;
                }
                if (isUsernameNull && isPasswordNull) {
                    btn_login.setBackgroundResource( R.drawable.item_bg_blue_button );
                    btn_login.setEnabled( true );
                } else {
                    btn_login.setBackgroundResource( R.drawable.item_bg_light_blue_button );
                    btn_login.setEnabled( false );
                }
            }
        } );

        password.addTextChangedListener( new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {

            }

            @Override
            public void afterTextChanged(Editable s) {

                if (s.toString().length() > 0) {
                    isPasswordNull = true;
                } else {
                    isPasswordNull = false;
                }
                if (isUsernameNull && isPasswordNull) {
                    btn_login.setBackgroundResource( R.drawable.item_bg_blue_button );
                    btn_login.setEnabled( true );
                } else {
                    btn_login.setBackgroundResource( R.drawable.item_bg_light_blue_button );
                    btn_login.setEnabled( false );
                }
            }
        } );
    }

    @OnClick(R.id.check_container)
    void check_container() {
        if (isCheckBox) {
            checkbox.setImageResource( R.mipmap.check );
        } else {
            checkbox.setImageResource( R.mipmap.check_focus );
        }
        isCheckBox = !isCheckBox;
    }

    @Override
    public void initState() {
//        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
//            Window window = this.getWindow();
//            //取消状态栏透明
//            window.clearFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
//            //添加Flag把状态栏设为可绘制模式
//            window.addFlags(WindowManager.LayoutParams.FLAG_DRAWS_SYSTEM_BAR_BACKGROUNDS);
//            //设置状态栏颜色
//            window.setStatusBarColor(Color.parseColor("#ffffff"));
//            //设置系统状态栏处于可见状态
//            getWindow().getDecorView().setSystemUiVisibility(View.SYSTEM_UI_FLAG_LIGHT_STATUS_BAR);
//
////            window.getDecorView().setSystemUiVisibility(View.SYSTEM_UI_FLAG_VISIBLE);
//            //让view不根据系统窗口来调整自己的布局
//            ViewGroup mContentView = (ViewGroup) window.findViewById(Window.ID_ANDROID_CONTENT);
//            View mChildView = mContentView.getChildAt(0);
//            if (mChildView != null) {
//                ViewCompat.setFitsSystemWindows(mChildView, false);
//                ViewCompat.requestApplyInsets(mChildView);
//            }
//        }
    }
}
